﻿using System.ComponentModel.DataAnnotations;
using System.Globalization;

namespace ApiLib.Common.Attributes.DataValidationAttributes;

/// <summary>
/// 需要日期，日期不能为空，不能为DateTime.MinValue
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class DateRequiredAttribute : ValidationAttribute
{
    /// <summary>
    /// 构造方法，默认返回异常信息：date can not be null
    /// </summary>
    public DateRequiredAttribute()
        : base(() => "date can not be null")
    {
    }

    /// <summary>
    /// 格式
    /// </summary>
    public string[] Format { get; set; } = ["yyyy-MM-dd HH:mm:ss", "yyyy/MM/dd HH:mm:ss", "yyyy/M/d H:mm:ss"];

    /// <summary>
    /// 验证
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public override bool IsValid(object? value)
    {
        if (value == null)
        {
            return false;
        }

        if (value is DateTime dt)
        {
            return dt != DateTime.MinValue;
        }

        return DateTime.TryParseExact(value.ToString() ?? "", Format, CultureInfo.CurrentCulture, DateTimeStyles.None,
            out var date) && date != DateTime.MinValue;
    }
}